/**
 * 
 */
package net.toocruel.iqismart.dao.spec;

import net.toocruel.iqismart.dao.condition.TagCondition;
import net.toocruel.iqismart.dao.support.BaseSpecification;
import net.toocruel.iqismart.dao.support.QueryWraper;
import net.toocruel.iqismart.entity.common.Tag;
import org.apache.commons.lang.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Root;

/**
 * @author toocruel
 *
 */
public class TagSpec extends BaseSpecification<Tag, TagCondition> {

	public TagSpec(TagCondition condition) {
		super(condition);
	}

	@Override
	protected void addCondition(QueryWraper<Tag> queryWraper) {
		CriteriaBuilder cb = queryWraper.getCb();
		Root<Tag> root = queryWraper.getRoot();

		if(StringUtils.isNotBlank(getCondition().getNameStart())){
			addStartsWidthCondition(queryWraper,"nameStart","name");
		}
		if(StringUtils.isNotBlank(getCondition().getName())){
			addEqualsCondition(queryWraper,"name");
		}
//		if(getCondition().getCategoryId()!=null && getCondition().getCategoryId()>0){

		if(getCondition().getCategoryId()!=null && getCondition().getCategoryId() == 0){
			getCondition().setCategoryId(null);
			cb.and(cb.isNull(root.get("category")));
		}else{
			addEqualsCondition(queryWraper,"categoryId","category");
		}

		if(getCondition().getIds()!=null && getCondition().getIds().length>0){
			addInCondition(queryWraper,"ids","id");
		}



	}

	@Override
	protected void addFetch(Root<Tag> root) {
		root.fetch("category");
	}
}
